define(["jquery","ztree","bbcare",
	"scprit/nutrition/app/departmentScheme/editScheme.ui.js",
	"scprit/nutrition/app/departmentScheme/editScheme.servers.js"],
	function($,ztree,$bb,$ui,$servers){
	var event = {};

	var $moveZtree = {
		setDragTreeDom: function(treeId,treeNodes){
			return treeNodes[0].isLeaf == "1" ? true : false;
		},
		dropTreeDom: function(e,treeId,treeNodes,targetNode,moveType){
			var domId = "platform";
			// 判断是否拖曳在目标元素(id:platform)里
			if( moveType == null && ( e.target.id == domId || $(e.target).parents("#" + domId).length > 0 ) ){
				/*var newDom = 
				'        <li domId=' + treeNodes[0].id + '>'+
                '            <div class="platform-left">'+
                '                <span class="num"></span>'+
                '                <span class="name">' + treeNodes[0].name + '</span>'+
                '            </div>'+
                '            <div class="platform-right">'+
                '                <span class="upMoveCourse"><i class="fa fa-arrow-circle-up" aria-hidden="true"></i> 上移</span>'+
                '                <span class="downMoveCourse"><i class="fa fa-arrow-circle-down" aria-hidden="true"></i> 下移</span>'+
                '                <span class="delCourse"><i class="fa fa-trash" aria-hidden="true"></i> 删除</span>'+
                '            </div>'+
                '        </li>';*/
                var $ul = $(e.target);
                var courseNo;
                if(e.target.id == domId){
                	//$ul.append(newDom);
                	courseNo = $ul.children("li").length;
                }else if($(e.target).parents("#" + domId).length > 0 ){
                	//$li.before(newDom);
					var $li = $ul.parents("li[stageCourseId]");
					courseNo = $li.index();
                }
				var stageId = $("#operationPeriod span.active").attr("stageId");
				var index = $("#operationPeriod span.active").index();
				var params = {
					"courseNo":(courseNo + 1).toString(),	
				    "courseId":treeNodes[0].refId,
				    "stageId":stageId,
				}
				$servers.ajaxStageCourseAdd(params,index,schemeDetails);
			}else{
				$bb.toastShow("放错了...请选择正确的位置！");
			}
		}
	};

	/**
	 * 查询疗程库菜单成功后的回调函数
	 */
	var ajaxCourseMenusCallBack = function(data){
	    var setting = {
	    	view: {
				selectedMulti: false
			},
			edit: {
				enable: true,
				showRemoveBtn: false,
				showRenameBtn: false,
				drag: {
					isCopy: true,
					isMove: false
				}
			},
	    	data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				beforeDrag: $moveZtree.setDragTreeDom,
				onDrop: $moveZtree.dropTreeDom
			}
	    };
	    $.fn.zTree.init($("#ztree"),setting,data);
    }

	/**
	 * 选择疗程库
	 */
	event.onCourseChange = function(){
        var libraryId = $(this).val();
        $servers.ajaxCourseMenus(libraryId,ajaxCourseMenusCallBack);
	}

	/**
	 * 上移疗程
	 */
	var onUpMoveCourse = function(){
		var stageCourseId = $(this).parents("li").attr("stageCourseId");
		var courseNo = Number($(this).parents("li").attr("courseNo"));
		var index = $("#operationPeriod span.active").index();
		if(courseNo > 1){
			courseNo -= 1;
			var params = {
				"stageCourseId":stageCourseId,
				"toCourseNo":courseNo.toString()
			}
			$servers.ajaxStageCourseMove(params,index,schemeDetails);
		}else{
			$bb.toastShow("该疗程已处于第一位，请不要再往上移动了！");
		}
	}

	/**
	 * 下移疗程
	 */
	var onDownMoveCourse = function(){
		var stageCourseId = $(this).parents("li").attr("stageCourseId");
		var courseNo = Number($(this).parents("li").attr("courseNo"));
		var lastCourseNo = $(this).parents("ul").find("li").last().attr("courseNo");
		var index = $("#operationPeriod span.active").index();
		if(courseNo < lastCourseNo){
			courseNo += 1;
			var params = {
				"stageCourseId":stageCourseId,
				"toCourseNo":courseNo.toString()
			}
			$servers.ajaxStageCourseMove(params,index,schemeDetails);
		}else{
			$bb.toastShow("该疗程已处于最后一位，请不要再往下移动了！");
		}
	}

	/**
	 * 删除疗程
	 */
	var onDelCourse = function(){
		var stageCourseId = $(this).parents("li").attr("stageCourseId");
		var index = $("#operationPeriod span.active").index();
		var params = {
			"stageCourseId":stageCourseId,
			"callback":schemeDetails,
			"index":index
		}
		$bb.toastConfirmShow($servers.ajaxStageCourseDel,params,"确定删除该疗程吗？");
	}

	/**
	 * 选择阶段进行切换,得到对应的疗程
	 */
	var onStagesSelect = function(){
		$(this).addClass("active").siblings().removeClass("active");
		var stages = $(this).data("stages");
		var stageId = $(this).attr("stageId");
		$ui.stageCoursesInit({
        	"id":"platform",
            "list":stages,
            "stageId":stageId
        });
        $("#platform .upMoveCourse").unbind("click");
        $("#platform .upMoveCourse").click(onUpMoveCourse);
        $("#platform .downMoveCourse").unbind("click");
        $("#platform .downMoveCourse").click(onDownMoveCourse);
        $("#platform .delCourse").unbind("click");
        $("#platform .delCourse").click(onDelCourse);
	}

	/**
	 * 点击“添加”按钮后，填入阶段名称后 保存功能
	 */
	var onSaveStageBlur = function(){
		var stageName = $(this).val();
		var params = $(this).data();
		var stageId = $(this).parent("span").attr("stageId");
		if(stageName != ""){
			var index = $(this).parent().index();
			$servers.ajaxSchemeStagesModify(stageName,stageId,params,index,schemeDetails);
		}else{
			$bb.toastShow("请输入阶段名称",1500);
			$(this).focus();
		}
	}

	/**
	 * 添加阶段
	 */
	var onAddStage = function(){
		var params = $(this).data();
		var h = '<span><input class="addStage" type="text"></span>';
		if($("#operationPeriod .addStage").length == 0){
			$("#operationPeriod").append(h);
		}
		$("#operationPeriod .addStage").focus();
		$("#operationPeriod .addStage").data(params);
		$("#operationPeriod .addStage").unbind("blur");
		$("#operationPeriod .addStage").blur(onSaveStageBlur);
	}

	/**
	 * 编辑阶段
	 */
	var onEditStage = function(){
		var params = $(this).data();
		var stageId = $("#operationPeriod span.active").attr("stageId");
		if($("#operationPeriod .editStage").length == 0){
			var pastStageName = $("#operationPeriod span.active").text();
		}else{
			var pastStageName = $("#operationPeriod .editStage").val();
		}
		var h = '<input class="editStage" type="text">';
		$("#operationPeriod span.active").html(h);
		$("#operationPeriod span.active").css({"backgroundColor":"#fff","color":"#333"});
		$("#operationPeriod .editStage").focus();
		$("#operationPeriod .editStage").val(pastStageName);
		$("#operationPeriod .editStage").data(params);
		$("#operationPeriod .editStage").unbind("blur");
		$("#operationPeriod .editStage").blur(onSaveStageBlur);
	}

	/**
	 * 删除阶段
	 */
	var onDelStage = function(){
		var stageId = $("#operationPeriod span.active").attr("stageId");
		var index = $("#operationPeriod span.active").index()-1;
		var length = $("#operationPeriod span").length;
		if(length > 0){
			var params = {
				"stageId":stageId,
				"callback":schemeDetails,
				"index":index
			};
			$bb.toastConfirmShow($servers.ajaxSchemeStagesDel,params,"确定删除该营养阶段吗？");
		}else{
			$bb.toastShow("当前方案还未添加营养阶段，请添加成功后删除",1500);
		}
	}

	/**
	 * 前移阶段
	 */
	var onForwardMoveStage = function(){
		var $span = $("#operationPeriod span.active");
		var stageId = $span.attr("stageId");
		var stageNo = Number($span.attr("stageNo"));
		var index = $span.index()-1;
		if(stageNo > 1){
			stageNo -= 1;
			var params = {
				"stageId":stageId,
				"toStageNo":stageNo.toString()
			}
			$servers.ajaxSchemeStagesMove(params,index,schemeDetails);
		}else{
			$bb.toastShow("该阶段已处于第一位，请不要再往前移动了！");
		}
	}

	/**
	 * 后移阶段
	 */
	var onBackMoveStage = function(){
		var $span = $("#operationPeriod span.active");
		var stageId = $span.attr("stageId");
		var stageNo = Number($span.attr("stageNo"));
		var index = $span.index()+1;
		var lastStageNo = $("#operationPeriod span").last().attr("stageNo");
		if(stageNo < lastStageNo){
			stageNo += 1;
			var params = {
				"stageId":stageId,
				"toStageNo":stageNo.toString()
			}
			$servers.ajaxSchemeStagesMove(params,index,schemeDetails);
		}else{
			$bb.toastShow("该阶段已处于最后一位，请不要再往后移动了！");
		}
	}

	/**
     * 请求营养方案详情成功后的回调函数
     */
    var ajaxSchemeDetailsCallBack = function(data,index,params){
        $ui.schemeDetailInit({
            "id":"schemeInfo",
            "data":data
        });
        // 为了解决删除最后一个成功后，显示却还在的情况
        var list = data.stages ? data.stages : [];
        $ui.schemeStagesInit({
            "id":"operationPeriod",
            "list":list
        });
        $("#operationPeriod span").data({"stages":data.stages});
        $("#operationPeriod span").click(onStagesSelect);
		$("#operationPeriod span").eq(index).click();

        $("#addStage").data(params);
        $("#addStage").unbind("click");
        $("#addStage").click(onAddStage);
        $("#editStage").data(params);
        $("#editStage").unbind("click");
        $("#editStage").click(onEditStage);
        $("#delStage").unbind("click");
        $("#delStage").click(onDelStage);
        $("#forwardMoveStage").unbind("click");
        $("#forwardMoveStage").click(onForwardMoveStage);
        $("#backMoveStage").unbind("click");
        $("#backMoveStage").click(onBackMoveStage);
    }

    /**
	 * 根据schemeVersionId、schemeId请求营养方案详情
	 */
	var schemeDetails = function(index){
		var params = $servers.getPageParams();
		$servers.ajaxSchemeDetails(params,index,ajaxSchemeDetailsCallBack);
	}
	event.schemeDetails = function(index){
		schemeDetails(index);
	}

	/**
	 * 发布方案
	 */
	event.onSchemePublish = function(){
		var schemeId = $(this).data("params").schemeId;
		$servers.ajaxSchemePublish(schemeId);
	}

	/**
	 * 删除方案成功后的回调函数
	 */
	var ajaxSchemeDeleteCallBack = function(data){
		$bb.openPage("departmentScheme");
	}

	/**
	 * 删除方案
	 */
	event.onSchemeDel = function(){
		var params = $(this).data("params");
		params.fn = ajaxSchemeDeleteCallBack;
		$bb.toastConfirmShow($servers.ajaxSchemeDelete,params,"确定删除该方案吗？");
	}

	return event;
});